<?php

namespace App\CommandModel;

use App\Helpers\Helpers;
use App\Model\Express;

//批量查询物流
class TrackingMore
{
    public function runStatusQuery()
    {
        $track = new \App\Helpers\Trackingmore();

        $i = 1;
        $s = 0;
        $t = 0;
        while (true) {
            $res = $track->getTrackingsList($i,100,time()-7*24*3600,time());
            if ($res && $res['meta']['code'] == 200) {
                $i++;
                $items = $res['data']['items'];

                foreach ($items as $item) {
                    $e = Express::where('tracking_number','=',$item['tracking_number'])
                        ->where('carrier_code','=',$item['carrier_code'])
                        ->where('out_trade_no','=',$item['order_id'])
                        ->first();

                    if ($e) {
                        $e->tracking_id = $item['id'];
                        $e->status = $item['status'];
                        $e->content = json_encode($item);
                        $e->last_query_time = time();
                        $e->save();
                        $s++;
                    }
                    $t++;
                }

                if ($res['data']['page']*$res['data']['limit'] > $res['data']['total']) {
                    break;
                }
            }
        }

        $items = Express::where('last_query_time','<',time()-7*24*3600)
            ->where('status','=','delivered')
            ->get();


        foreach ($items as $item) {
            if ($item->updateTrackingRealTime()) $s++;
            $t++;
        }

        Helpers::log('runStatusQuery: total:'.$t.' success:'.$s,'cmd');
    }
}
